package com.ruoyi.trainingManagement.controller;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.trainingManagement.domain.CourseScheduleDetails;
import com.ruoyi.trainingManagement.domain.Vo.AdjustmentDTO;
import com.ruoyi.trainingManagement.service.ICourseScheduleDetailsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.trainingManagement.domain.CourseAdjustmentRecord;
import com.ruoyi.trainingManagement.service.ICourseAdjustmentRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 调整课程记录表Controller
 * 
 * @author chenxl
 * @date 2025-08-14
 */
@RestController
@RequestMapping("/trainingManagement/CourseAdjustmentRecord")
public class CourseAdjustmentRecordController extends BaseController
{
    @Autowired
    private ICourseAdjustmentRecordService courseAdjustmentRecordService;
    @Autowired
    private ICourseScheduleDetailsService courseScheduleDetailsService;

    /**
     * 查询调整课程记录表列表
     */
    //@PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseAdjustmentRecord courseAdjustmentRecord)
    {
        startPage();
        List<CourseAdjustmentRecord> list = courseAdjustmentRecordService.selectCourseAdjustmentRecordList(courseAdjustmentRecord);
        return getDataTable(list);
    }

    /**
     * 导出调整课程记录表列表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:export')")
    @Log(title = "调整课程记录表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseAdjustmentRecord courseAdjustmentRecord)
    {
        List<CourseAdjustmentRecord> list = courseAdjustmentRecordService.selectCourseAdjustmentRecordList(courseAdjustmentRecord);
        ExcelUtil<CourseAdjustmentRecord> util = new ExcelUtil<CourseAdjustmentRecord>(CourseAdjustmentRecord.class);
        util.exportExcel(response, list, "调整课程记录表数据");
    }

    /**
     * 获取调整课程记录表详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(courseAdjustmentRecordService.selectCourseAdjustmentRecordById(id));
    }

    /**
     * 新增调整课程记录表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:add')")
    @Log(title = "调整课程记录表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseAdjustmentRecord courseAdjustmentRecord)
    {
        return toAjax(courseAdjustmentRecordService.insertCourseAdjustmentRecord(courseAdjustmentRecord));
    }

    /**
     * 修改调整课程记录表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:edit')")
    @Log(title = "调整课程记录表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateCourseAdjustmentRecord(@RequestBody CourseAdjustmentRecord courseAdjustmentRecord)
    {
        return toAjax(courseAdjustmentRecordService.updateCourseAdjustmentRecord(courseAdjustmentRecord));
    }

    /**
     * 删除调整课程记录表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:remove')")
    @Log(title = "调整课程记录表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(courseAdjustmentRecordService.deleteCourseAdjustmentRecordByIds(ids));
    }

    /**
     * 插入课程调整记录，根据调整范围决定是否更新课程详情
     * @param dto 包含调整记录和课程详情的DTO
     * @return 操作结果
     */
    @PostMapping("/insertAdjustmentRecord")
    public AjaxResult insertAdjustmentRecord(@RequestBody AdjustmentDTO dto) {
        System.out.println("接收dto数据: " + dto);
        // 校验参数合法性
        if (dto.getAdjustmentRecord() == null) {
            return AjaxResult.error("调整记录信息不能为空");
        }

        CourseAdjustmentRecord record = dto.getAdjustmentRecord();
        String adjustmentRange = record.getAdjustmentRange();

        try {
            // 插入调整记录
            int insertCount = courseAdjustmentRecordService.insertCourseAdjustmentRecord(record);
            if (insertCount <= 0) {
                return AjaxResult.error("新增调整记录失败");
            }

            // 当调整范围为"1"时，需要更新课程详情
            if ("1".equals(adjustmentRange)) {
                // 校验课程详情参数
                if (dto.getScheduleDetails() == null) {
                    return AjaxResult.error("调整范围为1时，课程详情信息不能为空");
                }

                int updateCount = courseScheduleDetailsService.updateCourseScheduleDetails(dto.getScheduleDetails());
                if (updateCount <= 0) {
                    // 这里可以根据业务需求决定是否回滚已插入的记录
                    return AjaxResult.error("新增调整记录成功，但更新课程详情失败");
                }
            }

            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            return AjaxResult.error("服务器异常，处理失败");
        }
    }

    /**
     * 通过原教师ID查询所有对应的调整记录
     * @param originalTeacherId 原教师ID
     * @return 调整记录列表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseAdjustmentRecord:list')")
    @GetMapping("/byOriginalTeacher/{originalTeacherId}")
    public AjaxResult selectAdjustmentRecordByOriginalTeacherId(@PathVariable String originalTeacherId) {
        System.out.println("selectAdjustmentRecordByOriginalTeacherId接收originalTeacherId数据: " + originalTeacherId);
        // 1. 参数校验
        if (originalTeacherId == null || originalTeacherId.trim().isEmpty()) {
            return AjaxResult.error("原教师ID不能为空");
        }

        try {
            // 2. 调用Service层查询
            List<CourseAdjustmentRecord> records = courseAdjustmentRecordService.selectAdjustmentRecordByOriginalTeacherId(originalTeacherId);
            System.out.println("selectAdjustmentRecordByOriginalTeacherId返回数据: " + records);
            // 3. 返回结果（即使为空也返回成功，前端根据列表长度判断）
            return AjaxResult.success(records);
        } catch (Exception e) {
            // 4. 异常处理
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
}
